package com.duqc.util;

import lombok.SneakyThrows;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.operators.relational.ExpressionList;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.schema.Table;
import net.sf.jsqlparser.statement.Statement;
import net.sf.jsqlparser.statement.select.GroupByElement;
import net.sf.jsqlparser.statement.select.PlainSelect;
import net.sf.jsqlparser.statement.select.Select;

/**
 * @ClassName JsqlparseUtil
 * @Description SQL解析
 * @Author duqc
 * @Date 2023/3/17
 **/
public class JsqlparseUtil {

    private JsqlparseUtil() {

    }

    /**
     * select 语句解析
     *
     * @param sql sql
     */
    @SneakyThrows
    public static void select(String sql) {
        Statement statement = CCJSqlParserUtil.parse(sql);
        if (statement instanceof Select) {
            Select select = (Select) statement;
            PlainSelect plainSelect = (PlainSelect) select.getSelectBody();
            Table table = (Table) plainSelect.getFromItem();
            System.out.println(table.getAlias().getName());
            System.out.println(table.getName());

            Expression expression = plainSelect.getWhere();
            System.out.println(expression);

            GroupByElement groupBy = plainSelect.getGroupBy();
            ExpressionList groupByExpressionList = groupBy.getGroupByExpressionList();
            System.out.println(groupBy);


            System.out.println(plainSelect);
        }

    }

    public static void main(String[] args) {
        select("SELECT ID,NAME FROM AA a WHERE bb = '111' AND (ff = '222' OR vv = '333') AND dd IS NOT NULL GROUP BY CC,dd ORDER BY EE DESC,rr DESC");
    }

}
